package com.example.zjx8969.myapplication;

import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 用于聊天页面，聊天消息框内的通知类型左边有个头像，右边是个箭头，中间是通知消息，解决因为布局原因把右边的箭头顶出去了
 * Created by zjx8969 on 2018/1/22.
 */

public class AutoMaxSizeTextLinearLayout extends LinearLayout {

    public AutoMaxSizeTextLinearLayout(Context context) {
        this(context, null);
    }

    public AutoMaxSizeTextLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measuredWidth = getMeasuredWidth();
        TextView textViewContent = null;
        int childCount = getChildCount();
        int totalWidth = getPaddingLeft() + getPaddingRight();
        int textViewWidth = 0;
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getVisibility() == GONE) return;
            if (childView instanceof TextView) {
                textViewContent = (TextView) childView;
                textViewWidth = childView.getMeasuredWidth();
            }
            LayoutParams layoutParams = (LayoutParams) childView.getLayoutParams();

            int cellWidth = childView.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin;
            totalWidth = totalWidth + cellWidth;
        }
        if (totalWidth > measuredWidth && textViewContent != null) {
            int available = measuredWidth - (totalWidth - textViewWidth);
            textViewContent.measure(MeasureSpec.makeMeasureSpec(available, MeasureSpec.EXACTLY), heightMeasureSpec);
        }
    }
}
